package com.sky.aspect;

import com.sky.annotation.AutoFill;
import com.sky.constant.AutoFillConstant;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Aspect
@Component
@Slf4j
public class AutoFillAspect {

    @Pointcut("@annotation(com.sky.annotation.AutoFill)")
    public void autoFillPoinycut(){}

    @Before("autoFillPoinycut()")
    public void autoFill(JoinPoint jp){

        log.info("开始自动填充");
        //获得方法的类型 是insert还是update
       // AutoFill annotation = jp.getClass().getAnnotation(AutoFill.class);
        MethodSignature signature = (MethodSignature)jp.getSignature();
        AutoFill annotation = signature.getMethod().getAnnotation(AutoFill.class);
        OperationType value = annotation.value();
        //获得方法的参数
        Object[] args = jp.getArgs();
        Object obj = args[0];  //约定传参的第一个必须为对象
        if(obj == null){  //如果没有参数 直接返回
            return;
        }
        //准备填充的数据
        LocalDateTime now = LocalDateTime.now();
        Long currentId = BaseContext.getCurrentId();

        //判断类型 反射填充
        if(value == OperationType.INSERT){  //更新四个
            try {
                Method createTime = obj.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME,LocalDateTime.class);
                Method updateTime = obj.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME,LocalDateTime.class);
                Method createUser = obj.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_USER,Long.class);
                Method updateUser = obj.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER,Long.class);
                //通过反射  填充数据
                createTime.invoke(obj,now);
                updateTime.invoke(obj,now);
                createUser.invoke(obj,currentId);
                updateUser.invoke(obj,currentId);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        } else if (value == OperationType.UPDATE) {  //更新两个
            try {
                Method updateTime = obj.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME,LocalDateTime.class);
                Method updateUser = obj.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER,Long.class);
                updateTime.invoke(obj,now);
                updateUser.invoke(obj,currentId);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }
}
